<template>
  <div class="login">
    <h1>This is login page</h1>
    <div class="login-block" @keyup.enter="login">
      <div class="input-group">
        用户名：
        <input type="text" v-model="form.account">
      </div>
      <div class="input-group">
        &nbsp;&nbsp;&nbsp;&nbsp;密码：
        <input type="password" v-model="form.password">
      </div>
      <br>
      <div>
        <button class="btn" @click="login">登录</button>
      </div>
    </div>
  </div>
</template>

<script>
import store from '@/store';

export default {
  data() {
    return {
      form: {
        account: '13760212887',
        password: '',
      },
    };
  },
  beforeRouteEnter(to, from, next) {
    store.dispatch('checkLogin').then((flag) => {
      console.log('flag', flag);
      next('/');
    }).catch(() => {
      next();
    });
  },
  methods: {
    login() {
      console.log('login', this.form);
      this.checkForm(this.form).then(() => {
        console.log('check ok');
        this.$store.dispatch('userLogin', {
          account: this.form.account,
        }).then(() => {
          this.$router.replace(this.url);
        });
      }).catch(() => {
        console.log('checkForm error')
      });
    },
    checkForm(form) {
      const phoneReg = /^1\d{10}$/;
      const emailReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/; ;
      if (!phoneReg.test(form.account) && !emailReg.test(form.account)) {
        this.msg('请输入正确的手机号码或者邮箱地址');
        return Promise.reject();
      }
      if (form.password.length < 6) {
        this.msg('密码必须大于 6 位数');
        return Promise.reject();
      }
      return Promise.resolve();
    },
  },
  computed: {
    url() {
      return this.$route.query.url || '/';
    },
  },
};
</script>

<style lang="less">
.login-block {
  display: inline-block;
  border-radius: 5px;
  padding: 50px;
  border: 1px solid #ccc;
  .input-group {
    line-height: 38px;
    font-size: 16px;
    input {
      // height: 20px;
      padding: 5px 10px;
    }
  }
}
</style>
